﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;
using System.Threading;
using System.Data.SqlClient;
using System.Collections.Generic;


namespace Cash
{
    public partial class Cash : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Boolean status = verificaConexao();
            lblDataHora.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Now);


            string[] words = HttpContext.Current.Request.Url.ToString().Split(new char[] { '/', '.' });
            string menu = words[words.Length - 3];
            string pagina = words[words.Length - 2];

            if (!IsPostBack)
            {

                Session.Timeout = 10;
                // Session["Usuario"] = " Faça seu login.";
                Session["ModuloAtivo"] = "";

                if (pagina != "BemVindo" && menu == "View")
                {
                    Despesa1Despesa.Visible = false;
                    Configuracao1Configuracao.Visible = false;
                    lblTitulo.Visible = false;
                    lblNome.Text = "Visitante.";
                }
                else
                {
                    try
                    {
                        lblNome.Text = Session["username"].ToString();
                    }
                    catch (Exception)
                    {
                        lblNome.Text = "Visitante.";
                        Session["username"] = "THIAGO.SILVERIO";
                        Session["iduser"] = "2";
                        Session["perfil"] = "1";
                        //Response.Redirect("~/View/Login.aspx");
                    }
                }
            }

            tituloPagina();
            UltimaPaginaVisitada();
        }

        private void tituloPagina()
        {
            PAGINA pagina = new PAGINA();
            PERFIL perfil = new PERFIL();
            CashEntities cashEntity = new CashEntities();
            String descricaoTitulo = "";
            String strPaginaAtual = Request.CurrentExecutionFilePath;
            strPaginaAtual = strPaginaAtual.Remove(0, strPaginaAtual.LastIndexOf("/") + 1);

            try
            {
                List<String> permitidos = new List<String>(){"PermissaoNegada.aspx",
                                                            "Login.aspx",
                                                            "RecuperaSenha.aspx",
                                                            "SistemaEmManutencao.aspx",
                                                            "BemVindo.aspx",
                                                            "CriarConta.aspx"};

                if (!permitidos.Contains(strPaginaAtual))
                {
                    pagina = cashEntity.PAGINA.Where(pag => pag.URL == strPaginaAtual).First();

                    int perfilSessao = Int32.Parse(Session["perfil"].ToString());
                    perfil = cashEntity.PERFIL.Where(c => c.ID_PERFIL == perfilSessao).First();

                    var dadosPermissao = (from perPag in cashEntity.PERFIL_PAGINA
                                          where perPag.ID_PERFIL == perfil.ID_PERFIL &&
                                                perPag.ID_PAGINA == pagina.ID_PAGINA &&
                                                perPag.ID_STATUS == 1
                                          select new
                                          {
                                              perPag.ID_PERFIL_PAGINA
                                          }).SingleOrDefault();

                    if (dadosPermissao == null)
                    {
                        Session["PermissaoNegada"] = strPaginaAtual;
                        Response.Redirect("~/View/PermissaoNegada.aspx?id=" + pagina.URL.ToString());
                    }
                }
            }
            catch (Exception)
            {
                Session["PermissaoNegada"] = strPaginaAtual;
                Response.Redirect("~/View/PermissaoNegada.aspx");
            }


            while (true)
            {
                if (pagina.ID_PAGINA_PAI == null)
                {
                    break;
                }
                else
                {
                    descricaoTitulo = pagina.NOME + " -> " + descricaoTitulo;
                    pagina = cashEntity.PAGINA.Where(pag => pag.ID_PAGINA == pagina.ID_PAGINA_PAI).First();
                }
            }

            lblTitulo.Text = "".Equals(descricaoTitulo) ? descricaoTitulo : descricaoTitulo.Substring(0, descricaoTitulo.Length - 4);
        }

        protected void lnkMenu_Click(object sender, EventArgs e)
        {
            LinkButton b = (LinkButton)sender;
            string[] nome = b.ID.Split('1');
            Session["ModuloAtivo"] = nome[0];
            IndicaMenus();
            String url = "~/View/" + nome[0] + "/" + nome[1] + ".aspx";
            if (nome[0].Equals("Ajuda"))
            {
                url = "~/View/" + nome[0] + "/" + "manualUsuario" + ".pdf";
            }
            Response.Redirect(url);
        }

        private void IndicaMenus()
        {
            String modulo = Session["ModuloAtivo"].ToString();
            lblTitulo.Text = "";
            switch (modulo)
            {
                case "Despesa":
                    return;
                case "Configuracao":
                    return;
                default:
                    return;
            }
        }

        private void UltimaPaginaVisitada()
        {
            List<String> permitidos = new List<String>(){"PermissaoNegada.aspx",
                                                         "SistemaEmManutencao.aspx"};
            PAGINA pagina = new PAGINA();
            String strPaginaAtual = Request.CurrentExecutionFilePath;
            String strValidaPaginaAtual = strPaginaAtual.Remove(0, strPaginaAtual.LastIndexOf("/") + 1);

            if (!permitidos.Contains(strValidaPaginaAtual))
            {
                Session["UltimaPagina"] = strPaginaAtual;
            }
        }

        private Boolean verificaConexao()
        {
            var db = new CashEntities();
            try
            {
                db.CommandTimeout = 1;
                db.Connection.Open();   // check the database connection
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}